<template>
  <div class="wraps">
    <div
      :style="{
        height: item.height + 'px',
        background: item.background,
        left: item.left + 'px',
        top: item.top + 'px',
      }"
      v-for="(item, index) in waterList"
      :key="index"
      class="items"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

const list = ref<any[]>([
  {
    height: 300,
    background: "red",
  },
  {
    height: 200,
    background: "blue",
  },
  {
    height: 100,
    background: "green",
  },
  {
    height: 500,
    background: "red",
  },
  {
    height: 400,
    background: "green",
  },
  {
    height: 700,
    background: "red",
  },
  {
    height: 600,
    background: "green",
  },
  {
    height: 100,
    background: "blue",
  },
  {
    height: 100,
    background: "red",
  },
  {
    height: 100,
    background: "gray",
  },
  {
    height: 100,
    background: "green",
  },
  {
    height: 100,
    background: "skyblue",
  },
]);

const waterList = ref<any[]>([]);
const heightList = ref<number[]>([]);

const init = () => {
  const width = 130;
  const x = document.body.clientWidth; // 浏览器可视区域宽度
  const column = Math.floor(x / width); // 一行显示几列

  list.value.forEach((_item, i) => {
    if (i < column) {
      list.value[i].left = i * width;
      list.value[i].top = 20;
      waterList.value.push(list.value[i]);
      heightList.value.push(list.value[i].height);
    } else {
      let currentHeight = heightList.value[0];
      let index = 0;

      heightList.value.forEach((h, i) => {
        if (currentHeight > h) {
          currentHeight = h;
          index = i;
        }
      });

      list.value[index].top = currentHeight + 20;
      list.value[index].left = index * width;
      heightList.value[index] =
        heightList.value[index] + list.value[index].height + 20;
      waterList.value.push(list.value[index]);
    }
  });
};

onMounted(() => {
  init();
});
</script>

<style scoped lang="scss">
.wraps {
  position: relative;

  .items {
    position: absolute;
    width: 120px;
  }
}
</style>
